package cn.larry.tools.sms;

import cn.larry.tools.cons.Constants;
import cn.larry.tools.http.HttpTool;
import cn.larry.tools.string.StringTool;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;

/**
 * Larry
 * 2022/1/4 16:32
 * 昂网短信工具
 *
 * @Version 1.0
 */
public class AngwangSmsTool {

    private static volatile AngwangSmsTool instance;

    public static AngwangSmsTool getInstance(String spCode,
                                             String loginName,
                                             String password) {
        if (instance == null) {
            synchronized (AngwangSmsTool.class) {
                if (instance == null) {
                    instance = new AngwangSmsTool(spCode,
                            loginName,
                            password);
                }
            }
        }
        return instance;
    }

    private AngwangSmsTool(String spCode,
                           String loginName,
                           String password) {
        this.spCode = spCode;
        this.loginName = loginName;
        this.password = password;
    }

    /**
     * 企业编号
     */
    private String spCode;

    /**
     * 用户名称
     */
    private String loginName;

    /**
     * 用户密码
     */
    private String password;

    /**
     * 单条（立即）短信发送
     *
     * @param messageContent 短信内容, 最大700个字符
     * @param userNumber     手机号码(多个号码用”,”分隔)，最多50000个号码
     * @return
     * @throws Exception
     */
    public String sendOne(String messageContent,
                          String userNumber) throws Exception {

        StringBuffer sb = new StringBuffer();
        sb.append("LoginName=").append(loginName)
                .append("&MessageContent=").append(URLEncoder.encode(messageContent, Constants.CODING_NAME_UTF8_UPCASE))
                .append("&Password=").append(password)
                .append("&SpCode=").append(spCode)
                .append("&UserNumber=").append(userNumber);

        String url = "http://47.104.84.72:8513/sms/Api/ReturnJson/Send.do";
        return HttpTool.sendPost(url, sb.toString());
    }

    /**
     * 单条（立即）短信发送，返回是否发送成功
     *
     * @param content
     * @param phone
     * @return
     * @throws Exception
     */
    public Boolean sendOneToResultFlag(String content,
                                       String phone) throws Exception {
        String resp = sendOne(content, phone);
        if (StringTool.isBlank(resp))
            return false;
        JSONObject jsonObject = JSONObject.parseObject(resp);
        Object object = jsonObject.get("result");
        if (object == null)
            return false;

        if (!"0".equals(object.toString()))
            return false;

        return true;
    }


}
